import { apiDomain, uploadUrl } from "@/constant";
import Taro from "@tarojs/taro";

export const chooseImage = () => {
  return new Promise<string>((resolve, reject) => {
    Taro.chooseImage({
      count: 1, // 默认9, 设置图片的数量
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        resolve(res.tempFilePaths[0]);
      },
      fail: (err) => {
        console.log("用户未选择图片", err);
        reject(err);
      }
    });
  });
};

export const uploadFile = (filePath: string) => {
  return new Promise<{ path: string }>((resolve, reject) => {
    Taro.uploadFile({
      url: uploadUrl,
      filePath: filePath,
      name: "file",
      success: (res: any) => {
        resolve(JSON.parse(res.data).file);
      },
      fail: (err) => { }
    });
  });
};

export const uploadFileByForm = (url: string, filePath: string, formData: any) => {
  return new Promise<any>((resolve, reject) => {
    const authorizationPrefix = 'Bearer ';
    const token = Taro.getStorageSync('access_token');
    Taro.uploadFile({
      url: apiDomain + url, // 替换为实际的上传接口地址
      filePath: filePath,
      name: 'file', // 与后端 FileInterceptor('file') 对应
      header: {
        'content-type': 'multipart/form-data',
        authorization: token ? authorizationPrefix + token : '',
      },
      formData: formData,
      success: (res: any) => {
        // console.log("上传成功", res);
        resolve(JSON.parse(res.data));
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

export const imageToBlob = (imageUrl: string) => {
  return new Promise<string>((resolve, reject) => {
    Taro.getFileSystemManager().readFile({
      filePath: imageUrl,
      encoding: "base64",
      success: (res) => {
        resolve(res.data as string);
      },
      fail: (err) => {
        console.log("图片解析成base64失败", err);
        reject(err);
      }
    });
  });
};
